<script lang="ts" setup>
// 导入 store 和所需组件
import type { ApplicationAddRequest } from "@/pages/internship/application/appliction-student/apis/type"
import { Briefcase, Calendar, Check, Location, Promotion, Star } from "@element-plus/icons-vue"
import { ElButton, ElMessage, ElTag } from "element-plus"
import { computed, watch } from "vue"
import { useApplicationStore } from "@/pinia/stores/application"
import { usePositionStudentStore } from "@/pinia/stores/position-student"
import { useUserStore } from "@/pinia/stores/user"

// 使用 store
const store = usePositionStudentStore()
const applicationStore = useApplicationStore()

// 监听positionDetail变化
watch(
  () => store.positionDetail,
  (newDetail) => {
    console.log("职位详情已更新:", newDetail)
  },
  { deep: true }
)

// 申请职位的方法
async function handleApplyPosition() {
  try {
    if (!store.positionDetail) {
      ElMessage.warning("请先选择职位")
      return
    }

    // 打开简历选择对话框
    await applicationStore.openResumeDialog()
  } catch (error) {
    console.error("打开简历选择对话框失败:", error)
    ElMessage.error("申请失败，请稍后重试")
  }
}

// 确认申请职位
async function confirmApplyPosition() {
  try {
    if (!applicationStore.selectedResume) {
      ElMessage.warning("请选择简历")
      return
    }

    if (!store.positionDetail) {
      ElMessage.warning("请先选择职位")
      return
    }

    const userStore = useUserStore()
    const userId = userStore.userInfo?.userId

    if (!userId) {
      ElMessage.warning("用户信息不存在，请重新登录")
      return
    }

    // 构建申请数据
    const applicationData: ApplicationAddRequest = {
      positionId: store.positionDetail.id,
      resumeId: applicationStore.selectedResume.resumeId,
      userId,
      resumeUrl: applicationStore.selectedResume.resumeUrl || ""
    }

    const success = await applicationStore.applyPosition(applicationData)

    if (success) {
      ElMessage.success("申请成功")
      applicationStore.closeResumeDialog()
      // 刷新职位详情，更新isApply状态
      if (store.positionDetail?.id) {
        await store.fetchPositionDetail(store.positionDetail.id)
      }
      // 刷新职位列表，确保列表中的状态也得到更新
      store.fetchList()
    } else {
      ElMessage.error(applicationStore.submitError || "申请失败")
    }
  } catch (error) {
    console.error("申请职位失败:", error)
    ElMessage.error("申请失败，请稍后重试")
  }
}

// 收藏职位的方法
function handleFavorite() {
  console.log("收藏职位:", store.positionDetail?.id)
  // 这里可以添加收藏逻辑
}

// 格式化文本为数组以便换行显示
function formatText(text: string | undefined) {
  if (!text) return []

  // 如果文本包含序号格式，按序号分割
  if (text.includes("1. ")) {
    return text.split(/(?=\d+\. )/).filter(line => line.trim())
  }

  return [text]
}

// 计算属性，用于模板中使用
const formattedPositionDesc = computed(() => formatText(store.positionDetail?.positionDesc))
const formattedPositionRequire = computed(() => formatText(store.positionDetail?.positionRequire))
</script>

<template>
  <!-- 使用 store 中的状态 -->
  <div v-if="store.detailLoading" class="loading-state">
    <p>加载中...</p>
  </div>
  <div class="position-detail" v-else-if="store.positionDetail">
    <div class="detail-header">
      <div class="title-section">
        <h2 class="position-title">
          {{ store.positionDetail.positionName || '职位名称' }}
        </h2>
        <div class="action-buttons-header">
          <ElButton size="large" class="favorite-btn" @click="handleFavorite">
            <Star /> 收藏
          </ElButton>
          <ElButton
            v-if="!store.positionDetail?.isApply"
            type="primary"
            size="large"
            class="apply-btn"
            @click="handleApplyPosition"
          >
            <Promotion /> 立即报名
          </ElButton>
          <ElButton
            v-else
            type="success"
            size="large"
            disabled
          >
            <Check /> 已报名
          </ElButton>
        </div>
      </div>
      <div class="salary">
        {{ store.positionDetail.salary || '薪资面议' }}
      </div>
      <div class="location-info">
        <div class="info-item" v-if="store.positionDetail.workCity">
          <Location class="info-icon" />
          <span>{{ store.positionDetail.workCity }}</span>
        </div>
        <div class="info-item" v-if="store.positionDetail.workType">
          <Briefcase class="info-icon" />
          <span>{{ store.positionDetail.workType }}</span>
        </div>
        <div class="info-item" v-if="store.positionDetail.period">
          <Calendar class="info-icon" />
          <span>{{ store.positionDetail.period }}</span>
        </div>
      </div>
      <div class="tags">
        <ElTag size="small" v-for="(tag, index) in (store.positionDetail.tags || [])" :key="index" type="info">
          {{ tag }}
        </ElTag>
      </div>
    </div>

    <div class="detail-section">
      <h3 class="section-title">
        职位描述
      </h3>
      <div class="section-content">
        <div v-for="(line, index) in formattedPositionDesc" :key="index" class="desc-item">
          {{ line }}
        </div>
      </div>
    </div>

    <div class="detail-section">
      <h3 class="section-title">
        任职要求
      </h3>
      <div class="section-content">
        <div v-for="(line, index) in formattedPositionRequire" :key="index" class="desc-item">
          {{ line }}
        </div>
      </div>
    </div>

    <div class="company-info">
      <h3 class="section-title">
        公司信息
      </h3>
      <div class="company-name">
        {{ store.positionDetail.companyName }}
      </div>
    </div>

    <div class="detail-section">
      <h3 class="section-title">
        工作地点
      </h3>
      <div class="section-content">
        {{ store.positionDetail.workPlace }}
      </div>
    </div>

    <div class="position-meta">
      <div class="meta-item">
        <span class="meta-label">招聘人数：</span>
        <span class="meta-value">{{ store.positionDetail.recruitNum }}人</span>
      </div>
      <div class="meta-item">
        <span class="meta-label">开始日期：</span>
        <span class="meta-value">{{ store.positionDetail.startDate }}</span>
      </div>
      <div class="meta-item">
        <span class="meta-label">截止日期：</span>
        <span class="meta-value">{{ store.positionDetail.deadline }}</span>
      </div>
      <div class="meta-item">
        <span class="meta-label">发布时间：</span>
        <span class="meta-value">{{ store.positionDetail.publishTime }}</span>
      </div>
    </div>
  </div>
  <div v-else class="empty-state">
    <p>请选择一个职位查看详情</p>
  </div>

  <!-- 简历选择对话框 -->
  <el-dialog
    v-model="applicationStore.isResumeDialogVisible"
    title="选择简历"
    width="500px"
    :before-close="applicationStore.closeResumeDialog"
  >
    <div v-loading="applicationStore.isLoadingResumes">
      <div v-if="applicationStore.userResumes.length === 0" class="no-resume">
        <p>暂无可用简历，请先创建简历</p>
        <ElButton type="primary" @click="$router.push('/internship/resume/add')">
          创建简历
        </ElButton>
      </div>
      <div v-else class="resume-list">
        <div class="resume-options">
          <div
            v-for="resume in applicationStore.userResumes"
            :key="resume.resumeId"
            class="resume-option"
            :class="{ 'resume-option--selected': applicationStore.selectedResume?.resumeId === resume.resumeId }"
            @click="applicationStore.selectResume(resume)"
          >
            <div class="resume-option__content">
              <div class="resume-option__radio">
                <div class="resume-option__radio-inner" v-if="applicationStore.selectedResume?.resumeId === resume.resumeId" />
              </div>
              <div class="resume-option__info">
                <span class="resume-option__name">{{ resume.resumeName }}</span>
                <ElTag v-if="resume.isDefault === 1" size="small" type="success">
                  默认
                </ElTag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="applicationStore.closeResumeDialog">取消</ElButton>
        <ElButton
          type="primary"
          :disabled="!applicationStore.selectedResume"
          :loading="applicationStore.isSubmitting"
          @click="confirmApplyPosition"
        >
          确认申请
        </ElButton>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.position-detail {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  min-height: 400px;
  max-height: calc(100vh - 200px);
}

// 确保父容器也有适当的高度设置
:deep(.el-scrollbar__wrap) {
  overflow-y: auto;
}

.detail-header {
  margin-bottom: 24px;
}

.title-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f3f4f6;
}

.action-buttons-header {
  display: flex;
  gap: 12px;
}

.position-title {
  font-size: 22px;
  font-weight: 600;
  margin: 0;
  color: #1f2937;
  flex: 1;
  padding-right: 20px;
}

.salary {
  font-size: 18px;
  color: #ef4444;
  font-weight: 500;
  margin-bottom: 8px;
}

.location-info {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;

  .info-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: #6b7280;

    .info-icon {
      width: 16px;
      height: 16px;
      color: #6b7280;
    }
  }
}

.tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.detail-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
}

.section-content {
  font-size: 14px;
  line-height: 1.6;
  color: #374151;

  .desc-item {
    margin-bottom: 12px;
    line-height: 1.8;
  }

  .desc-item:last-child {
    margin-bottom: 0;
  }
}

.company-info {
  margin-bottom: 24px;
}

.company-name {
  font-size: 16px;
  color: #374151;
  font-weight: 500;
}

.position-meta {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.meta-item {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.meta-label {
  color: #6b7280;
  width: 80px;
}

.meta-value {
  color: #374151;
  flex: 1;
}

.favorite-btn {
  background-color: #fff;
  border-color: #d1d5db;
  color: #6b7280;
  font-weight: 500;

  .el-icon {
    margin-right: 4px;
  }
}

.favorite-btn:hover {
  border-color: #f59e0b;
  color: #f59e0b;
}

.apply-btn {
  background-color: #3b82f6;
  border-color: #3b82f6;
  font-weight: 500;

  .el-icon {
    margin-right: 4px;
  }
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #6b7280;
}

/* 增强滚动条样式，添加更多浏览器兼容性 */
.scrollable-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.scrollable-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.scrollable-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  transition: background 0.2s;
}

.scrollable-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 添加对Firefox的支持 */
.scrollable-content {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

/* 简历选择对话框样式 */
.no-resume {
  text-align: center;
  padding: 20px;

  p {
    margin-bottom: 16px;
    color: #6b7280;
  }
}

.resume-list {
  max-height: 300px;
  overflow-y: auto;
}

.resume-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.resume-option {
  padding: 12px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: #3b82f6;
    background-color: #f8fafc;
  }

  &.resume-option--selected {
    border-color: #3b82f6;
    background-color: #eff6ff;
  }
}

.resume-option__content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.resume-option__radio {
  width: 16px;
  height: 16px;
  border: 2px solid #d1d5db;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;

  .resume-option--selected & {
    border-color: #3b82f6;
  }
}

.resume-option__radio-inner {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #3b82f6;
}

.resume-option__info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;

  .resume-option__name {
    font-weight: 500;
    color: #1f2937;
  }
}
</style>
